package com.huawei.chengdu.meetingdemo.view.adapter;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.device.idea.meeting.MeetingCallback;
import com.device.idea.meeting.Share.model.ShareAction;
import com.device.idea.meeting.Share.model.ShareCastSrcType;
import com.device.idea.meeting.Share.model.ShareCurInfo;
import com.device.idea.meeting.Share.model.ShareSpecificInfo;
import com.device.idea.meeting.Share.model.ShareStartInfo;
import com.device.idea.meeting.Share.model.ShareType;
import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.model.ShareDataInfo;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.util.ScreenUtil;
import com.huawei.chengdu.meetingdemo.view.MeetingControlView;

import java.util.ArrayList;
import java.util.List;

public class ShareItemAdapter extends RecyclerView.Adapter<ShareItemAdapter.ShareItemListViewHolder> {
    private final List<ShareDataInfo> shareDataInfoList;
    private Context mContext;
    private PackageManager packageManager;

    public ShareItemAdapter(List<ShareDataInfo> shareDataInfos, Context context) {
        mContext = context;
        packageManager = context.getPackageManager();
        shareDataInfoList = new ArrayList<>();
        updateShareDataList(shareDataInfos);
    }

    public void updateShareDataList(List<ShareDataInfo> newShareDataList) {
        shareDataInfoList.clear();
        shareDataInfoList.addAll(newShareDataList);
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public ShareItemListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_share, parent, false);
        return new ShareItemListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ShareItemListViewHolder holder, int position) {
        ShareDataInfo shareDataInfo = shareDataInfoList.get(position);
        LogUtil.info("share data info = " + shareDataInfo);
        if (shareDataInfo.getShareType() == ShareType.CAST) {
            holder.shareName.setText(getCastName(shareDataInfo.getShareCastInfo().getCastSrcType()));
        } else if (shareDataInfo.getShareType() == ShareType.APP){
            holder.shareName.setText(getAppName(shareDataInfo.getShareAppInfo().getAppPackName()));
        } else if (shareDataInfo.getShareType() == ShareType.WHITEBOARD){
            holder.shareName.setText(mContext.getString(R.string.white_board));
        }  else {
            LogUtil.error("unSupport shareType=" + shareDataInfo.getShareType());
            holder.shareName.setText("app");
        }
        changeButtonStatus(holder, isInSharing(shareDataInfo));
        holder.buttonShare.setOnClickListener(v -> {
            if (holder.isInShare) {
                stopShare(holder);
            } else {
                startShare(shareDataInfo, holder);
            }
        });
    }

    @Override
    public int getItemCount() {
        return shareDataInfoList.size();
    }

    public class ShareItemListViewHolder extends RecyclerView.ViewHolder {
        private TextView shareName;
        private TextView buttonShare;
        private boolean isInShare = false;

        public ShareItemListViewHolder(@NonNull View itemView) {
            super(itemView);
            shareName = itemView.findViewById(R.id.share_name);
            buttonShare = itemView.findViewById(R.id.button_share);
        }
    }

    private String getCastName(ShareCastSrcType shareCastSrcType) {
        switch (shareCastSrcType) {
            case WIRELESS:
                return "无线投屏";
            case HDMI:
                return "有线投屏(HDMI)";
            case WINDOWS:
                return "Windows应用";
            case TYPEC:
                return "有线投屏(Type-C)";
            default:
                return "有线投屏";
        }
    }

    private void startShare(ShareDataInfo shareDataInfo, ShareItemListViewHolder holder) {
        MeetingControlView.shareItemSelectDialog.dismiss();
        if (!Settings.canDrawOverlays(mContext)) {
            Toast.makeText(mContext, "未开启悬浮窗权限，无法共享", Toast.LENGTH_LONG).show();
            ScreenUtil.requestFloatWindowRight(mContext);
            return;
        }
        ShareStartInfo shareStartInfo = new ShareStartInfo();
        shareStartInfo.setShareType(shareDataInfo.getShareType());
        ShareSpecificInfo shareSpecificInfo = new ShareSpecificInfo();
        if (shareDataInfo.getShareType() == ShareType.APP) {
            shareSpecificInfo.setAppInfo(shareDataInfo.getShareAppInfo());
        } else if (shareDataInfo.getShareType() == ShareType.CAST){
            shareSpecificInfo.setCastInfo(shareDataInfo.getShareCastInfo());
        } else if (shareDataInfo.getShareType() == ShareType.WHITEBOARD){
            shareSpecificInfo.setCastInfo(shareDataInfo.getShareCastInfo());
        } else {
            LogUtil.error("unSupport shareType=" + shareDataInfo.getShareType());
            return;
        }
        shareStartInfo.setShareSpecificInfo(shareSpecificInfo);
        ConfSdkPresenter.startShare(shareStartInfo, new MeetingCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                LogUtil.info("Start share success");
                changeButtonStatus(holder, true);
            }

            @Override
            public void onFailed(int errCode, String errMsg) {
                LogUtil.error("Start share fail, errCode = " + errCode + " errMsg = " + errMsg);
            }
        });
    }

    private void stopShare(ShareItemListViewHolder holder) {
        ConfSdkPresenter.stopShare(new MeetingCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                LogUtil.info("Stop share success");
                changeButtonStatus(holder, false);
            }

            @Override
            public void onFailed(int errCode, String errMsg) {
                LogUtil.error("Stop share fail, errCode = " + errCode + " errMsg = " + errMsg);
            }
        });
    }

    private String getAppName(String packageName) {
        try {
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            return packageManager.getApplicationLabel(applicationInfo).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "获取APP信息异常";
        }
    }

    private void changeButtonStatus(ShareItemListViewHolder holder, boolean isInShare) {
        holder.isInShare = isInShare;
        holder.buttonShare.post(() -> {
            holder.buttonShare.setText(isInShare ? "停止共享" : "共享");
            holder.buttonShare.setBackgroundResource(isInShare ? R.drawable.conf_button_background_color : R.drawable.share_dialog_text_shape);
        } );
    }

    private boolean isInSharing(ShareDataInfo shareDataInfo) {
        ShareCurInfo shareCurInfo = ConfSdkPresenter.getCurShareInfo();
        if (shareCurInfo.getShareAction() != ShareAction.ACTION_SENDING) {
            return false;
        }
        if (shareCurInfo.getShareType() == ShareType.APP && shareDataInfo.getShareType() == ShareType.APP &&
                shareCurInfo.getShareSpecificInfo().getAppInfo().getAppPackName().equals(shareDataInfo.getShareAppInfo().getAppPackName())) {
            return true;
        }

        if (shareCurInfo.getShareType() == ShareType.CAST && shareDataInfo.getShareType() == ShareType.CAST) {
            return true;
        }
        return false;
    }
}
